﻿using Anke.SHManage.IDAL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Anke.SHManage.Model.BasicEventInfo;
using System.Reflection;

namespace Anke.SHManage.MSSQLDAL
{
    public class AcceptEventDAL : IAcceptEventDAL
    {
        //去除民族，是否需要担架
        public AcceptEventInfo GetAcceptEventInfoByCode(string code, int orderNum)
        {
            AcceptEventInfo AEinfo;
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
SELECT 事件编码=TAC.事件编码,受理序号=TAC.受理序号,受理类型编码,受理类型子编码,责任受理人编码,呼救电话=TAC.呼救电话
    ,挂起时刻,TAC.电话振铃时刻,TAC.开始受理时刻,TAC.结束受理时刻,发送指令时刻
    ,现场地址,等车地址,送往地点,往救地点类型编码,送往地点类型编码,联系人,联系电话,分机
    ,患者姓名,性别,年龄
    ,国籍,主诉,病种判断,TAC.病情编码,患者人数,特殊要求,是否标注
    ,X坐标,Y坐标,派车列表,备注=case when TAC.备注 is null or TAC.备注='' then TAC.MPDS备注 else TAC.备注 end
    ,TAC.中心编码,TAC.保留字段1,TAC.保留字段2,TZET.名称 as 受理类型,TP.姓名 as 责任受理人,病情=tzis.名称 
    ,往救地点类型=tzlat.名称,送往地点类型=tzsat.名称,责任受理人工号=tp.工号,中心名称=tc.名称
FROM TAcceptEvent TAC
left join TZAcceptEventType TZET on TZET.编码 = TAC.受理类型编码
left join TPerson TP on TP.编码 = TAC.责任受理人编码
left join TCenter TC on TC.编码 = TAC.中心编码
left join TZIllState tzis on tzis.编码 = TAC.病情编码
left join TZLocalAddrType tzlat on tzlat.编码 = TAC.往救地点类型编码
left join TZSendAddrType tzsat on tzsat.编码 = TAC.送往地点类型编码
where TAC.事件编码 = '" + code + @"' and TAC.受理序号='" + orderNum + @"'");
            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null))
            {
                AEinfo = new AcceptEventInfo();
                if (dr.Read())
                {
                    AEinfo.EventCode = DBConvert.ConvertStringToString(dr["事件编码"]);
                    AEinfo.AcceptOrder = Convert.ToInt32(dr["受理序号"]);
                    AEinfo.TypeId = Convert.ToInt32(dr["受理类型编码"]);
                    AEinfo.DetailReasonId = Convert.ToInt32(dr["受理类型子编码"]);
                    AEinfo.AcceptPersonCode = DBConvert.ConvertStringToString(dr["责任受理人编码"]);
                    AEinfo.AcceptPersonWorkID = DBConvert.ConvertStringToString(dr["责任受理人工号"]);
                    AEinfo.AlarmTel = DBConvert.ConvertStringToString(dr["呼救电话"]);
                    AEinfo.HangUpTime = DBConvert.ConvertNullableToNullableTime(dr["挂起时刻"].ToString());
                    AEinfo.RingTime = DBConvert.ConvertNullableToNullableTime(dr["电话振铃时刻"].ToString());
                    AEinfo.AcceptBeginTime = DBConvert.ConvertNullableToNullableTime(dr["开始受理时刻"].ToString());
                    AEinfo.AcceptEndTime = DBConvert.ConvertNullableToNullableTime(dr["结束受理时刻"].ToString());
                    AEinfo.CommandTime = DBConvert.ConvertNullableToNullableTime(dr["发送指令时刻"].ToString());
                    AEinfo.LocalAddr = DBConvert.ConvertStringToString(dr["现场地址"]);
                    AEinfo.WaitAddr = DBConvert.ConvertStringToString(dr["等车地址"]);
                    AEinfo.SendAddr = DBConvert.ConvertStringToString(dr["送往地点"]);
                    AEinfo.LocalAddrTypeId = Convert.ToInt32(dr["往救地点类型编码"]);
                    AEinfo.SendAddrTypeId = Convert.ToInt32(dr["送往地点类型编码"]);
                    AEinfo.LinkMan = DBConvert.ConvertStringToString(dr["联系人"]);
                    AEinfo.LinkTel = DBConvert.ConvertStringToString(dr["联系电话"]);
                    AEinfo.Extension = DBConvert.ConvertStringToString(dr["分机"]);
                    AEinfo.PatientName = DBConvert.ConvertStringToString(dr["患者姓名"]);
                    AEinfo.Sex = DBConvert.ConvertStringToString(dr["性别"]);
                    AEinfo.Age = DBConvert.ConvertStringToString(dr["年龄"]);
                    //AEinfo.Folk = DBConvert.ConvertStringToString(dr["民族"]);
                    AEinfo.National = DBConvert.ConvertStringToString(dr["国籍"]);
                    AEinfo.AlarmReason = DBConvert.ConvertStringToString(dr["主诉"]);
                    AEinfo.Judge = DBConvert.ConvertStringToString(dr["病种判断"]);
                    AEinfo.IllStateId = Convert.ToInt32(dr["病情编码"]);
                    //AEinfo.IsNeedLitter = Convert.ToBoolean(dr["是否需要担架"]);
                    AEinfo.PatientCount = Convert.ToInt32(dr["患者人数"]);
                    AEinfo.SpecialNeed = DBConvert.ConvertStringToString(dr["特殊要求"]);
                    AEinfo.IsLabeled = Convert.ToBoolean(dr["是否标注"]);
                    AEinfo.X = Convert.ToDouble(dr["X坐标"]);
                    AEinfo.Y = Convert.ToDouble(dr["Y坐标"]);
                    AEinfo.AmbulanceList = DBConvert.ConvertStringToString(dr["派车列表"]);
                    AEinfo.Remark = DBConvert.ConvertStringToString(dr["备注"]);
                    AEinfo.AcceptType = DBConvert.ConvertStringToString(dr["受理类型"]);
                    AEinfo.Dispatcher = DBConvert.ConvertStringToString(dr["责任受理人"]);
                    AEinfo.IllState = DBConvert.ConvertStringToString(dr["病情"]);
                    AEinfo.LocalAddrType = DBConvert.ConvertStringToString(dr["往救地点类型"]);
                    AEinfo.SendAddrType = DBConvert.ConvertStringToString(dr["送往地点类型"]);
                    AEinfo.AcceptPersonWorkID = DBConvert.ConvertStringToString(dr["责任受理人工号"]);
                    AEinfo.BackUpOne = DBConvert.ConvertStringToString(dr["保留字段1"]);
                    AEinfo.BackUpTwo = DBConvert.ConvertStringToString(dr["保留字段2"]);
                    AEinfo.CenterName = DBConvert.ConvertStringToString(dr["中心名称"].ToString());
                }              
            }
            AEinfo.DetailReason = "";
              StringBuilder sb2 = new StringBuilder();
            if (AEinfo.TypeId == 1 || AEinfo.TypeId == 3 || AEinfo.TypeId == 8)//挂起
            { sb.Append(@"
SELECT * FROM TZHangUpReason t where 编码 = '" + AEinfo.TypeId + @"'");
            }
            else if (AEinfo.TypeId == 4)//回车
            {sb.Append(@"
SELECT * FROM TZRejectReason t where 编码 = '" + AEinfo.TypeId + @"'"); }
            else if (AEinfo.TypeId == 6)//撤销待派
            { sb.Append(@"
SELECT * FROM TZDropReason t where 编码 = '" + AEinfo.TypeId + @"'");}
            else if (AEinfo.TypeId == 7)//改派派车
            { sb.Append(@"
SELECT * FROM TZReassignmentReason t where 编码 = '" + AEinfo.TypeId + @"'");}
            else
            { }
            if (sb2.ToString().Length > 0)
            {
                using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.AttemperConnectionString, CommandType.Text, sb2.ToString(), null))
                {
                    if (dr.Read())
                    { AEinfo.DetailReason = DBConvert.ConvertStringToString(dr["名称"].ToString()); }
                }
            }
            return AEinfo;
        }

        public AcceptEventInfo GetEventNode(string code)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append(@"  select  受理次数, 事件编码
                        from TAlarmEvent A
                         where A.事件编码='" + code + @"'
                    ");
            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null))
            { // DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                AcceptEventInfo ENinfo = new AcceptEventInfo();
                if (dr.Read())
                {
                    ENinfo.EventCode = DBConvert.ConvertStringToString(dr["事件编码"]);
                    ENinfo.AcceptOrder = Convert.ToInt32(dr["受理次数"]);
                }
                return ENinfo;
            }
        }
        //return ds.Tables[0];

        //获取年龄
        public object GetAge()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAge
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;
        }

        #region 保存修改受理信息 2016-10-28
        public bool UpdateAccept(string EventCode, string AlarmReason, string PatientName, string Sex, string Age, string National, string Folk,
                string Judge, string LinkMan, string LinkTel, string Extension, string LocalAddr, string WaitAddr, string SendAddr, bool IsNeedLitter)
        {
            try
            {
                StringBuilder strSQL = new StringBuilder();

                strSQL.Append(@"update TAcceptEvent set 主诉='" + AlarmReason + "',患者姓名='" + PatientName + "', 性别='" + Sex + "',年龄='" + Age + "',国籍='" + National + "'");
                strSQL.Append(@",民族='" + Folk + "',病种判断='" + Judge + "',联系人='" + LinkMan + "',联系电话='" + LinkTel + "',分机='" + Extension + "',现场地址='" + LocalAddr + "'");
                strSQL.Append(@",等车地址='" + WaitAddr + "',送往地点='" + SendAddr + "',是否需要担架='" + IsNeedLitter + "'");
                strSQL.Append(@" where 事件编码='" + EventCode + "'");

                int ds = SqlHelper.ExecuteNonQuery(SqlHelper.AttemperConnectionString, CommandType.Text, strSQL.ToString(), null);
                return ds > 0 ? true : false;

            }
            catch (Exception ex)
            {
                LogUtility.Error("AcceptEventDAL/UpdateAccept()", ex.ToString());
                return false;
            }
        }

        private static Dictionary<string, int> m_ModifyAcceptTypeDic = null;
        public string ModifyAccept(AcceptEventInfo info, string operatorCode)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(SqlHelper.AttemperConnectionString))
                {

                    DataBase db = new DataBase(con);
                    AcceptEventInfo originInfo = (from aei in db.AcceptEventInfo
                                                    where aei.EventCode == info.EventCode
                                                    select aei).FirstOrDefault();
                    if (originInfo == null)
                        return "没有找到对应的任务实体";

                    #region 更新主表
                    m_ModifyAcceptTypeDic = new Dictionary<string, int>();
                    m_ModifyAcceptTypeDic.Add("AlarmReason", 19);//主诉---数字对应表[TZModifyRecordType]该修改项的类型编码
                    m_ModifyAcceptTypeDic.Add("IsNeedLitter", 22);//是否需要担架
                    m_ModifyAcceptTypeDic.Add("PatientName", 14);//患者姓名
                    m_ModifyAcceptTypeDic.Add("Sex", 15);//性别
                    m_ModifyAcceptTypeDic.Add("Age", 16);//年龄
                    m_ModifyAcceptTypeDic.Add("National", 18);//国籍

                    m_ModifyAcceptTypeDic.Add("Folk", 17);//民族
                    m_ModifyAcceptTypeDic.Add("Judge", 20);//病种判断
                    m_ModifyAcceptTypeDic.Add("LinkMan", 11);//联系人
                    m_ModifyAcceptTypeDic.Add("LinkTel", 12);//联系电话
                    m_ModifyAcceptTypeDic.Add("Extension", 13);//分机
                    m_ModifyAcceptTypeDic.Add("LocalAddr", 6);//现场地址
                    m_ModifyAcceptTypeDic.Add("WaitAddr", 7);//等车地址
                    m_ModifyAcceptTypeDic.Add("SendAddr", 8);//送往地点
                    List<ModifyRecordInfo> mriList = new List<ModifyRecordInfo>();
                    //获得所有property的信息
                    PropertyInfo[] properties = originInfo.GetType().GetProperties();
                    foreach (PropertyInfo p in properties)
                    {
                        int typeId = -1;
                        if (m_ModifyAcceptTypeDic.TryGetValue(p.Name, out typeId)) //如果需要修改
                        {
                            object oldObj = p.GetValue(originInfo, null);
                            object newObj = p.GetValue(info, null);
                            string oldValue = oldObj == null ? "" : oldObj.ToString();
                            string newValue = newObj == null ? "" : newObj.ToString();
                            if (!object.Equals(oldValue, newValue))
                            {
                                p.SetValue(originInfo, newObj, null);
                                ModifyRecordInfo mri = new ModifyRecordInfo();
                                mri.Code = Guid.NewGuid();
                                mri.NewContent = newObj.ToString();//2011-02-14 如果是null就费了。
                                mri.OriginContent = oldObj.ToString();//2011-02-14 如果是null就费了。
                                mri.OperateTime = DateTime.Now;
                                mri.OperatorCode = operatorCode;
                                mri.TypeId = typeId;
                                mri.EventCode = originInfo.EventCode;
                                mri.AcceptOrder = originInfo.AcceptOrder;
                                //mri.TaskCode = originInfo.TaskCode();//任务编码
                                mriList.Add(mri);
                            }
                        }
                    }
                    db.ModifyRecordInfos.InsertAllOnSubmit(mriList);
                    #endregion
                    db.SubmitChanges();
                    return "";
                }
            }
            catch (Exception ex)
            { return ex.ToString(); }
        }

        /// <summary>
        /// 查询受理修改痕迹
        /// 20161030 周志猛 add
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowCount"></param>
        /// <param name="EventCode"></param>
        /// <returns></returns>
        public List<ModifyRecordInfo> GetAcceptCrackInfos(int pageIndex, int pageSize, ref int rowCount, string EventCode)
        {
            DataBase db = new DataBase(SqlHelper.AttemperConnectionString);

            var qry = (from alm in db.ModifyRecordInfos
                       join m in db.ModifyRecordTypeInfo on alm.TypeId equals m.BianMa into temp
                       join person in db.PersonInfo on alm.OperatorCode equals person.Code into tempPerson
                       from tt in temp.DefaultIfEmpty()
                       from p in tempPerson.DefaultIfEmpty()
                       where alm.EventCode == EventCode & alm.AcceptOrder!=null
                       select new
                       {
                           Code = alm.Code,
                           EventCode = alm.EventCode,
                           OperatorName = p == null ? "" : p.Name,//这里主要第二个集合有可能为空。需要判断
                           OperateTime = alm.OperateTime,
                           StringOperateTime = alm.OperateTime.ToString(),
                           TypeName = tt == null ? "" : tt.MingCheng,//这里主要第二个集合有可能为空。需要判断
                           OriginContent = alm.OriginContent,
                           NewContent = alm.NewContent
                       }).ToList();
            List<ModifyRecordInfo> list = new List<ModifyRecordInfo>();
            ModifyRecordInfo info = new ModifyRecordInfo();
            for (int i = 0; i < qry.Count; i++)
            {
                info = new ModifyRecordInfo();
                info.Code = (Guid)qry[i].Code;
                info.EventCode = qry[i].EventCode.ToString();
                info.OperatorName = qry[i].OperatorName.ToString();
                info.OperateTime = Convert.ToDateTime(qry[i].OperateTime);
                info.StringOperateTime = Convert.ToDateTime(qry[i].StringOperateTime).ToString("yyyy-MM-dd HH:mm:ss");
                info.TypeName = qry[i].TypeName.ToString();
                info.OriginContent = qry[i].OriginContent.ToString();
                info.NewContent = qry[i].NewContent.ToString();
                list.Add(info);
            }
            list = list.OrderByDescending(t => t.OperateTime).ToList();
            rowCount = qry.Count;
            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        #endregion
    }
}
